package com.ihome.android.market2.frag;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ihome.android.EAFragment;
import com.ihome.android.academy.DetailActivity;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.common.CategoryID;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.image.ImageLoader;
import com.ihome.android.image.ImageLoaderFactory;
import com.ihome.android.image.impl.DefaultImageLoadHandler;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.GetViewAppDetailTask;
import com.ihome.android.market2.asynctask.SearchAppTask;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.view.SearchAppItem;
import com.ihome.android.market2.view.PageLine;
import com.ihome.android.util.CustomKeyboard;
import com.ihome.android.util.log.LogUtil;
import com.iptv.player.IPTVPlayer;

public class SurfaceviewFragment extends EAFragment implements OnKeyListener {
	private final String		TAG					= SurfaceviewFragment.class.getSimpleName();
	private View				fragview;
	private int					mLocalCatg			= -1;

	@EAInjectView(id = R.id.main_surface)
	private SurfaceView			mSurfaceView;

	private Handler				mHandler;

	private ImageLoader			imageLoader;
	public static boolean		firstEnter			= true;

	/******* For video play *********/
	private static final int	MSG_VIDEO_PLAY		= 0X01;
	private IPTVPlayer			mPlayer;
	private SurfaceHolder		mSurfaceHolder		= null;
	private int					mSurfaceWidth		= -1;
	private int					mSurfaceHeight		= -1;
	/*	private boolean mPlayerReleased = false;
		private boolean mNeedStartPlay = false;*/
	public static int			VideoRetryTime		= 0;
	private boolean				mNeedStartPlay		= false;
	private boolean				mVideoInitialized	= false;
	private boolean				mPlayerReleased		= false;
	private boolean				isLive				= false;

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_VIDEO_PLAY:
					String url = (String) msg.obj;
					VideoRetryTime = 0;
					initPlayer();
					mPlayer.setProgramURL(url);
					mPlayer.setLive(isLive);
					mPlayer.start();
					mNeedStartPlay = false;
					break;
				default:
					break;
				}
			}
		};
	}

	@Override
	protected void setFragView() {
		mFragView = fragview;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		LogUtil.i(TAG, "--> onAttach");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		procHandler();

		imageLoader = ImageLoaderFactory.create(getActivity());
		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.icon_default);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		LogUtil.i(TAG, " -->  onCreateView()");
		fragview = (RelativeLayout) inflater.inflate(R.layout.frag_surfaceview, container, false);

		return fragview;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		init();
	}

	@Override
	public void onResume() {
		super.onResume();
		LogUtil.d(TAG, " --> onResume() ");
	}

	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		LogUtil.i(TAG, " -->  setArguments()");
	}

	public void focusView() {
		if (mLocalCatg != -1 && mLocalCatg == CategoryID.CATEGORY_SEARCH) {}
	}

	private void init() {
		LogUtil.i(TAG, " -->  init()");

		if (mSurfaceView == null) {
			LogUtil.d(TAG, " --> mSurfaceView == null");
		}
		else {
			initVideo();
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		LogUtil.v(TAG, " --> onKey() keyCode = " + keyCode);

		if (keyCode == 92 && event.getAction() == KeyEvent.ACTION_DOWN) {
			return true;
		}
		else if (keyCode == 93 && event.getAction() == KeyEvent.ACTION_DOWN) {
			return true;
		}
		return false;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		firstEnter = true;
	}

	private void startVideoPlay() {
		String playUrl = "rtsp://221.228.34.68:554/vod/23380900020010439627.mpg?userid=itvzhengh01&stbip=61.155.239.28&clienttype=1&mediaid=0000000030010009625363&ifcharge=1&time=20150803143724+08&life=172800&usersessionid=31135&vcdnid=vcdn001&boid=001&srcboid=001&columnid=391804&backupagent=221.228.34.68:554&ctype=1&playtype=0&Drm=0&EpgId=null&programid=23380900020010439627&contname=&fathercont=&bp=0&authid=&tscnt=0&tstm=0&tsflow=0&ifpricereqsnd=1&stbid=00100299007011500003C864C79D44D1&nodelevel=3&terminalflag=1&bitrate=0&usercharge=47D3B44B73B209A9CD3BE6DE83553308";
		Message msg = new Message();
		msg.obj = playUrl;
		msg.what = MSG_VIDEO_PLAY;
		mHandler.sendMessageDelayed(msg, 800);
	}

	@SuppressWarnings("deprecation")
	private void initVideo() {
		if (mSurfaceView == null)
			return;
		if (mPlayer == null) {
			mPlayer = IPTVPlayer.Instance();
		}
		mPlayer = IPTVPlayer.Instance();
		mSurfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);
		mSurfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
				if (null != holder.getSurface()) {
					mSurfaceHolder = holder;
					if (mSurfaceWidth != width || mSurfaceHeight != height) {
						mVideoInitialized = false;
						mSurfaceWidth = width;
						mSurfaceHeight = height;
					}
					initPlayer();

					if (mNeedStartPlay) {
						mNeedStartPlay = false;
						VideoRetryTime = 0;
						mPlayer.setLive(isLive);
						mPlayer.resume();
						Log.i("test", "onResume2");
					}
				}
			}

			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				// TODO Auto-generated method stub

			}

			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				mSurfaceHolder = null;
				mSurfaceWidth = -1;
				mSurfaceHeight = -1;
				releasePlayer();
			}
		});

		startVideoPlay();
	}

	private void initPlayer() {
		if (mSurfaceHolder != null && mSurfaceHolder.getSurface() != null && mSurfaceWidth > 0 && mSurfaceHeight > 0 && !mVideoInitialized) {
			Log.i("test", "initPlayer");
			mPlayer.initialize();
			mPlayer.setSurface(mSurfaceHolder.getSurface());

			int w = mPlayer.getSystemWidth();
			int h = mPlayer.getSystemHeight();

			Log.i("test", "w = " + w + "\th = " + h);
			mPlayer.setScrHW(w, h);

			int[] location = new int[2];
			mSurfaceView.getLocationOnScreen(location);

			/*			mPlayer.setVideoWindow((int) (location[0] * 1.5 + 0.5),
								(int) (location[1] * 1.5 + 0.5),
								(int) (mSurfaceWidth * 1.5 + 0.5),
								(int) (mSurfaceHeight * 1.5 + 0.5));*/
			Log.d(TAG, "location[0] = " + location[0] + "\tlocation[1] = " + location[1] + "\tmSurfaceWidth  = " + mSurfaceWidth + "\tmSurfaceHeight = " + mSurfaceHeight);
			//gy:replace up with following codes for video window right more
			mPlayer.setVideoWindow((int) location[0], (int) location[1], (int) (mSurfaceWidth), (int) (mSurfaceHeight));

			mPlayer.setAudioBalance(0);
			mVideoInitialized = true;
			mPlayerReleased = false;
		}
	}

	private void releasePlayer() {
		IPTVPlayer.setActivityPaused(false);
		if (mPlayerReleased) {
			return;
		}
		mPlayer.setLive(isLive);
		mPlayer.stop();
		mPlayer.release();
		mPlayerReleased = true;
	}

}
